﻿using Core.DataAccess.Model;
using Dapper;
using iTool.Interfaces;
using System;
using System.Linq;

namespace iTool.Implements
{
    public class ClientServicesCollection : IClientServicesCollection
    {
        private IDBFactory iDBFactory;

        private int seed = 0;

        private readonly int workingStatus = 3;

        public ClientServicesCollection(IDBFactory iDBFactory)
        {
            this.iDBFactory = iDBFactory;
        }

        public Uri GetService()
        {
            var c = this.GetClientService();

            if (c == default)
                return null;

            return new Uri($"{(c.isWss ? "wss" : "ws")}://{c.host}:{c.port}");
        }

        public Uri GetService(string token)
        {
            var c = this.GetClientService();

            if (c == default)
                return null;

            return new Uri($"{(c.isWss ? "wss" : "ws")}://{c.host}:{c.port}?{token}");

        }

        private ClientServices GetClientService()
        {
            using (var db = iDBFactory.Create())
            {
                var clients = db.GetList<ClientServices>($"where [status] = {workingStatus}");

                if (clients?.Count() > 0)
                {
                    return clients.OrderBy(s => Guid.NewGuid()).Take(1).FirstOrDefault();
                }
            }

            return default;
        }
    }
}